<?php
namespace app\admin\controller;

use app\admin\code\BaseCode;
use app\admin\logic\AuthLogic;
use app\admin\logic\LoginLogic;
use app\admin\logic\SystemLogic;
use app\admin\model\AuthModel;
use app\admin\util\Response;
use think\Config;
use think\Controller;
use think\Lang;
use think\Request;
use think\Session;

class Base extends Controller
{
    /**
     * 当前用户信息
     * @var
     */
    protected static $admin;
    /**
     * 当前模块
     */
    protected $_module;
    /**
     * 当前控制器
     */
    protected $_controller;
    /**
     * 当前动作
     */
    protected $_action;
    /**
     * 是否ajax
     */
    protected $_ajax;
    /**
     * 控制器初始化
     */
    protected function _initialize()
    {
        $this->_module = Request::instance()->module();
        $this->_controller = Request::instance()->controller();
        $this->_action = Request::instance()->action();
        $this->_ajax = Request::instance()->isAjax();
        $this->_check_auth();
        $this->_check_login();
        $logic = new SystemLogic();
        $logic->get_site_config();
        if($this->_ajax === false){//不需输出变量与菜单还有导航
            $this->_assign_common();
            $this->_assign_menu();
            $this->_assign_nav();
        }
        parent::_initialize();
    }

    /**
     * 检查登录权限
     */
    private function _check_login(){
        $logic = new LoginLogic();
        $loginCallBack = function(){
            $this->error(BaseCode::MUST_LOGIN,'',url('login/index'));
        };
        $logic->check_login(strtolower($this->_module),strtolower($this->_controller),strtolower($this->_action),$loginCallBack);
    }
    /**
     * 检查权限
     */
    private function _check_auth(){
        $logic = new AuthLogic();
        $authCallBack = function(){
            $this->error(BaseCode::NOT_AUTH,'');
        };
        $logic->auth(strtolower($this->_module),strtolower($this->_controller),strtolower($this->_action),$authCallBack);
    }
    /**
     * 默认输出到页面的变量
     */
    protected function _assign_common(){
        $this->assign('version','v1');
        $this->assign('admin_name',self::get_admin_info());
        $this->assign('system',Config::get('system'));
    }
    private function _assign_menu(){
        $where = array('is_menu'=>1);
        $admin = self::get_admin_info();
        if($admin['rule']){
            $where['id'] = array('in',$admin['rule']);
        }
        $where['status'] = 1;
        $model = new AuthModel();
        $menuList = $model->selectData($where,'*','sort asc');
        $temp = array();
        $module = strtolower($this->_module);
        $controller = strtolower($this->_controller);
        usort($menuList,function($a,$b){
            if($a['pid'] == 0 && $a['sort'] < $b['sort']){
                return false;
            }else{
                return true;
            }
        });
        foreach ($menuList as $k=>$v){
            if($v['module'] == $module && $v['controller'] == $controller ){
                $v['is_select'] = 1;
            }else{
                $v['is_select'] = 0;
            }
            if($v['pid'] == 0){
                if(isset($temp[$v['id']]['parent']['is_select'])){
                    $v['is_select'] = $temp[$v['id']]['parent']['is_select'];
                }
                $temp[$v['id']]['parent'] = $v;
            }else{
                if(!isset($temp[$v['pid']])){
                    $temp[$v['pid']]['parent'] = [];
                }
                $temp[$v['pid']]['child'][] = $v;
                if($v['is_select'] == 1 &&
                    (!isset($temp[$v['pid']]['parent']['is_select']) ||
                        $temp[$v['pid']]['parent']['is_select'] == 0)){
                    $temp[$v['pid']]['parent']['is_select'] = 1;
                }
            }
        }
        $menuList = [];
        foreach ($temp as $value){
            if(isset($value['parent']) && empty($value['parent']) === false){
                $menuList[] = $value;
            }
        }
        $this->assign('menuList',$menuList);
    }
    private function _assign_nav(){
        $model = new AuthModel();
        $where = [];
        $where['module'] = strtolower($this->_module);
        $where['controller'] = strtolower($this->_controller);
        $where['action'] = strtolower($this->_action);
        $auth = $model->findData($where);
        if($auth){
            $data = $model->get_nav_tree($auth['nav_pid'],[]);
            array_unshift($data,$auth);
            $this->assign('nav',array_reverse($data));
        }

    }


    /**
     * 获取当前管理员信息
     * @return bool
     */
    public static function get_admin_info(){
        if(self::$admin){
            return self::$admin;
        }else{
            $admin_info = Session::get('admin');
            if($admin_info){
                self::set_admin_info($admin_info);
                return self::$admin;
            }else{
                return false;
            }
        }
    }

    /**
     * 设置当前管理员信息
     * @param $info 管理员信息
     */
    public static function set_admin_info($info){
        self::$admin = $info;
    }


    /**
     * 输出错误
     * @param integer $code 错误码
     * @param string $msg 错误信息
     * @param array $data 数据
     * @param string $url 如果需要跳转url
     */
    protected function error($code,$msg = '',$url = '',$data = [])
    {
        if($msg == ''){
            $msg = Lang::get($code);
        }
        if(Request::instance()->isAjax()){
            $result = [];
            $result['code'] = $code;
            $result['msg'] = $msg;
            $result['data'] = $data;
            $result['url'] = $url;
            Response::sendJson($result);
        }else{
            parent::error($msg,$url,$data,2,[]);
        }
    }
}
